package demo3;

import javax.swing.tree.TreeNode;

/**
 * Created with IntelliJ IDEA.
 * Description:翻转二叉树(前序遍历)
 * User: liangyuanzhang
 * Date: 2025-4-22
 * Time: 0:47
 */
class Test {
    public TreeNode invertTree(TreeNode root) {
        if(root == null) return null;

        //如果到了最后一个叶子节点没必要换(优化)
        if(root.left == null && root.right == null) return root;

        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;

        //交换完之后分别递归左和右
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }

    //后序遍历 -- 递归有返回值接收
    public TreeNode invertTree(TreeNode root) {
        if (root == null) return null;

        // 后序遍历：先递归处理左右子树
        TreeNode left = invertTree(root.left);
        TreeNode right = invertTree(root.right);

        // 交换当前节点的左右子树
        root.left = right;
        root.right = left;

        return root;
    }
}



